package com.system.travel.modules.system.controller;

import com.system.travel.common.constant.BusinessConstants;
import com.system.travel.common.response.Result;
import com.system.travel.common.utils.CaptchaUtils;
import com.system.travel.common.utils.RedisUtils;
import com.system.travel.modules.system.dto.LoginDTO;
import com.system.travel.modules.system.service.AuthService;
import com.system.travel.modules.system.vo.LoginVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 认证Controller
 *
 * @author lucas
 * @date 2024/01/01
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private AuthService authService;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody @Valid LoginDTO loginDTO) {
        // 验证验证码
        Object cacheObj = redisUtils.get(BusinessConstants.CAPTCHA_CACHE_PREFIX + loginDTO.getCaptchaKey());
        String cacheCode = cacheObj != null ? String.valueOf(cacheObj) : null;
        
        if (cacheCode == null || !cacheCode.equalsIgnoreCase(loginDTO.getCaptcha())) {
            return Result.error("验证码错误或已过期");
        }
        
        // 验证通过后，删除验证码
        redisUtils.delete(BusinessConstants.CAPTCHA_CACHE_PREFIX + loginDTO.getCaptchaKey());
        
        LoginVO loginVO = authService.login(loginDTO.getUsername(), loginDTO.getPassword());
        return Result.success(loginVO);
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        authService.logout();
        return Result.success();
    }

    /**
     * 获取验证码
     */
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletResponse response, @RequestParam String key) throws IOException {
        // 生成验证码
        String code = CaptchaUtils.generateCaptchaCode();
        // 保存验证码到Redis
        redisUtils.set(BusinessConstants.CAPTCHA_CACHE_PREFIX + key, code, BusinessConstants.CAPTCHA_EXPIRE_TIME, TimeUnit.MINUTES);
        // 生成验证码图片
        BufferedImage image = CaptchaUtils.generateCaptchaImage(code);
        
        // 设置响应头
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        
        // 输出图片
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
} 